<?php

namespace addons\cms\controller\wxapp;

use addons\third\library\Service;
use addons\third\model\Third;
use app\admin\model\RecoveryCategory;
use app\admin\model\RecoveryOrder;
use app\admin\model\timetable\Usersetting;
use app\admin\model\UserAddress;
use app\admin\model\UserWithdrawal;
use fast\Http;
use think\Config;
use think\Db;
use think\Validate;

//骑手表

/**
 * 会员
 */
class User extends Base
{
	protected $noNeedLogin = ['index', 'login', 'riderList'];
	
	protected $token = '';
	
	public function _initialize()
	{
		$this->token = $this->request->post('token');
		if ($this->request->action() == 'login' && $this->token) {
			$this->request->post(['token' => '']);
		}
		parent::_initialize();
		
		if (!Config::get('fastadmin.usercenter')) {
			$this->error(__('User center already closed'));
		}
	}
	
	
	/**
	 * 登录
	 */
	public function login()
	{
		if ($this->auth->isLogin()) {
			$this->success("登录成功", ['userInfo' => $this->getUserInfo()]);
		}
		$config = get_addon_config('cms');
		$code = $this->request->post("code");
		$rawData = $this->request->post("rawData", '', 'trim');
		$userInfo = (array)json_decode($rawData, true);
		if (!$code || empty($userInfo)) {
			$this->error("参数不正确");
		}
		$third = get_addon_info('third');
		if (!$third || !$third['state']) {
			$this->error("请在后台插件管理安装并配置第三方登录插件");
		}
		
		$params = [
			'appid' => $config['wxappid'],
			'secret' => $config['wxappsecret'],
			'js_code' => $code,
			'grant_type' => 'authorization_code'
		];
		$result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
		if ($result['ret']) {
			$json = (array)json_decode($result['msg'], true);
			if (isset($json['openid'])) {
				//如果有传Token
				if ($this->token) {
					$this->auth->init($this->token);
					//检测是否登录
					if ($this->auth->isLogin()) {
						$third = Third::where(['openid' => $json['openid'], 'platform' => 'wxapp'])->find();
						if ($third && $third['user_id'] == $this->auth->id) {
							$this->success("登录成功", ['userInfo' => $this->getUserInfo()]);
						}
					}
				}
				
				$platform = 'wechat';
				$result = [
					'openid' => $json['openid'],
					'userinfo' => [
						'nickname' => $userInfo['nickName'],
					],
					'access_token' => $json['session_key'],
					'refresh_token' => '',
					'expires_in' => isset($json['expires_in']) ? $json['expires_in'] : 0,
					'apptype' => 'miniapp'
				];
				
				$extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
				$ret = Service::connect($platform, $result, $extend);
				if ($ret) {
					$this->success("登录成功", ['userInfo' => $this->getUserInfo()]);
				} else {
					$this->error("连接失败");
				}
			} else {
				$this->error("登录失败");
			}
		}
		
		return;
	}
	
	/**
	 * 绑定账号
	 */
	public function bind()
	{
		$account = $this->request->post("account");
		$password = $this->request->post("password");
		if (!$account || !$password) {
			$this->error("参数不正确");
		}
		
		$account = $this->request->post('account');
		$password = $this->request->post('password');
		$rule = [
			'account' => 'require|length:3,50',
			'password' => 'require|length:6,30',
		];
		
		$msg = [
			'account.require' => 'Account can not be empty',
			'account.length' => 'Account must be 3 to 50 characters',
			'password.require' => 'Password can not be empty',
			'password.length' => 'Password must be 6 to 30 characters',
		];
		$data = [
			'account' => $account,
			'password' => $password,
		];
		$validate = new Validate($rule, $msg);
		$result = $validate->check($data);
		if (!$result) {
			$this->error(__($validate->getError()));
			return false;
		}
		$field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
		$user = \app\common\model\User::get([$field => $account]);
		if (!$user) {
			$this->error('账号未找到');
		}
		$third = Third::where(['user_id' => $user->id, 'platform' => 'wxapp'])->find();
		if ($third) {
			$this->error('账号已经绑定其他小程序账号');
		}
		
		$third = Third::where(['user_id' => $this->auth->id, 'platform' => 'wechat', 'apptype' => 'miniapp'])->find();
		if (!$third) {
			$this->error('未找到登录信息');
		}
		
		if ($this->auth->login($account, $password)) {
			$third->user_id = $this->auth->id;
			$third->save();
			$this->success("绑定成功", ['userInfo' => $this->getUserInfo()]);
		} else {
			$this->error($this->auth->getError());
		}
	}
	
	/**
	 * 个人资料
	 */
	public function profile()
	{
		$user = $this->auth->getUser();
		$nickname = $this->request->post('nickname');
		$avatar = $this->request->post('avatar');
		$exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
		if ($exists) {
			$this->error(__('昵称已存在'));
		}
		$avatar = str_replace(cdnurl('', true), '', $avatar);
		if ($nickname) $user->nickname = $nickname;
		if ($avatar) $user->avatar = $avatar;
		$user->save();
		$this->success('', ['userInfo' => $this->getUserInfo()]);
	}
	
	/**
	 * 保存头像
	 */
	public function avatar()
	{
		$user = $this->auth->getUser();
		$avatar = $this->request->post('avatar');
		if (!$avatar) {
			$this->error("头像不能为空");
		}
		$avatar = str_replace(cdnurl('', true), '', $avatar);
		$user->avatar = $avatar;
		$user->save();
		$this->success('', ['userInfo' => $this->getUserInfo()]);
	}
	
	
	public function userInfo()
	{
		$this->success('', ['userInfo' => $this->getUserInfo()]);
	}
	
	/**
	 * 获取用户信息
	 * @return array
	 */
	protected function getUserInfo()
	{
		$userinfo = $this->auth->getUserInfo();
		$userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
		return $userinfo;
	}
	
	/**
	 * 退出登录
	 */
	public function logout()
	{
		$this->auth->logout();
		$this->success(__('Logout successful'));
	}
	
	/*用户订单列表*/
	public function orderList()
	{
		$status = $this->request->post('status');//获取订单状态筛选 4=待评价 其他值为全部
		$where['order_user_id'] = $this->auth->id;
		if ($status != -1) $where['recovery_order.status'] = $status;
		$model = new RecoveryOrder();
		$list = $model->where($where)
			->with(['rider'])
			->order('id DESC')
			->select();
		foreach ($list as &$row) {
			$row['ordertime_text'] = date("Y-m-d H:i", $row['ordertime']);
			$row['createtime_text'] = date("Y-m-d H:i:s", $row['createtime']);
			/*计算预计回收价格*/
			$goodsinfos = unserialize($row['goodsinfo']);
			$estimate_price = 0;
			foreach ($goodsinfos as $goodsinfo) {
				$data = RecoveryCategory::get($goodsinfo['recovery_category_id']);
				$price = isset($goodsinfo['price']) ? $goodsinfo['price'] : 0;
				$price = $data ? $data->price : $price;
				$estimate_price += (float)$price * (float)$goodsinfo['weight'];
			}
			$row['estimate_price'] = sprintf("%.2f", $estimate_price);
			/*计算实际回收的价格*/
			if ($row['real_goods_info']) {
				$realgoodsinfos = unserialize($row['real_goods_info']);
				$realestimate_price = 0;
				foreach ($realgoodsinfos as $realgoodsinfo) {
					$realestimate_price += floatval((float)$realgoodsinfo['price'] * (float)$realgoodsinfo['weight']);
				}
				$row['real_estimate_price'] = sprintf("%.2f", $realestimate_price);
			}
		}
		
		$this->success('', $list);
	}
	
	
	/*获取用户地址*/
	public function addressDetail()
	{
		$id = (int)$this->request->post('id');//地址id
		if (!$id) $this->error(__('Operation failed'));
		$address = UserAddress::get($id);
		if (!$address || ($address['user_id'] != $this->auth->id)) {
			$this->error(__('地址不存在'));
		}
		$this->success('', $address);
	}
	
	/*获取用户地址*/
	public function addAddress()
	{
		$data = stripslashes(html_entity_decode($this->request->post('data')));
		$data = json_decode($data, true);
		$address = UserAddress::get((int)$data['id']);
		$bool = false;
		if ($data['name'] == '') $this->error("请填写联系人姓名");
		if ($data['mobile'] == '') $this->error("请填写联系人电话");
		if ($data['address'] == '') $this->error("请选择取货地址");
		$data['defaultswitch'] = isset($data['defaultswitch']) ? (bool)$data['defaultswitch'] : 0;
		Db::startTrans();
		if ($address) {
			$bool = true;
			if ($data['defaultswitch']) {
				$addressUpdate = new UserAddress();
				$addressUpdate->where('id', '<>', $address->id)
					->where('user_id', $this->auth->id)
					->update(['defaultswitch' => 0]);
			}
		} else {
			$address = new UserAddress();
			if ($data['defaultswitch']) {
				$addressUpdate = new UserAddress();
				$addressUpdate->where('user_id', $this->auth->id)->update(['defaultswitch' => 0]);
			}
		}
		$address->name = $data['name'];
		$address->mobile = $data['mobile'];
		$address->address = $data['address'];
		$address->address_detail = $data['address_detail'];
		$address->defaultswitch = $data['defaultswitch'];
		$address->user_id = $this->auth->id;
		$address->lat = $data['lat'];
		$address->lng = $data['lng'];
		$result = $address->save();
		if ($result !== false) {
			Db::commit();
			$this->success($address ? '保存成功' : '添加成功');
		} else {
			$this->error($address ? '保存失败' : '添加失败');
		}
		
	}
	
	/*删除用户地址*/
	public function delAddress()
	{
		$id = (int)$this->request->post('id');//地址id
		if (!$id) $this->error(__('参数错误'));
		$address = UserAddress::get($id);
		if (!$address || ($address['user_id'] != $this->auth->id)) {
			$this->error(__('地址不存在'));
		} else {
			$address->delete();
		}
		$this->success('删除成功');
	}
	
	/*用户地址列表*/
	public function addressList()
	{
		$where['user_id'] = $this->auth->id;
		$model = new UserAddress();
		$list = $model->where($where)
			->order('id DESC')
			->select();
		foreach ($list as &$row) {
			$row['address'] = implode('', explode('/', $row['address']));
		}
		$this->success('', $list);
	}
	
	/*在线骑手列表*/
	public function riderList()
	{
		//经纬度
		$lat = $this->request->post('lat/f', 0);
		$lng = $this->request->post('lng/f', 0);
		$list = Usersetting::hasWhere('user', ['signstatus' => '1'])
			->order('id DESC')
			->select();
		$markers = [];
		foreach ($list as &$row) {
			$user = \app\common\model\User::get($row->user_id);
			if ($user) {
				if (!$row->user->lat || !$row->user->lng) continue;
				if ($row->user->lastactivitytime < time() - 30 * 60) continue;
			} else {
				continue;
			}
			/*判断是否已经申请为骑手*/
			$riderApply = \app\admin\model\RiderApply::where('status', 1)->where('user_id', $row->user->id)->count();
			if (!$riderApply) {
				continue;
			}
			
			/*计算骑手订单数量*/
			$orderCount = RecoveryOrder::where('rider_user_id', $user->id)
//                ->where( 'status', 'IN', [3,4])
				->count();
			$serviceAttitudeAvg = RecoveryOrder::where('rider_user_id', $user->id)
				->where('status', 'IN', [4])
				->avg('serviceAttitude');
			$punctuallyAvg = RecoveryOrder::where('rider_user_id', $user->id)
				->where('status', 'IN', [4])
				->avg('punctually');
			
			$item = [
				'id' => $row->user->id,
				'latitude' => $row->user->lat,
				'longitude' => $row->user->lng,
				'iconPath' => '/assets/images/location.png',
				'width' => 26,
				'height' => 30,
				'customCallout' => [
					'display' => 'ALWAYS'
				],
				'orderCount' => $orderCount,
				'serviceAttitude' => ($serviceAttitudeAvg + $punctuallyAvg) * 100 / 10,
				'nickname' => $user->nickname,
				'avatar' => strpos($user->avatar, 'http') === false ? cdnurl($user->avatar, true) : $user->avatar
			];
			
			$markers[] = $item;
		}
		//定位点按照最近距离排序
		if ($lat && $lng) {
			for ($i = 0, $len = count($markers); $i < $len - 1; $i++) {
				//把最大的值放到最左边。
				for ($j = 0; $j + 1 < $len - $i; $j++) {
					//两两相比
					//计算前后两个相对于 $lat和$lng的距离
					$a = ((float)$markers[$j]['latitude'] * 1 - $lat * 1) * ((float)$markers[$j]['latitude'] - $lat * 1) + ((float)$markers[$j]['longitude'] * 1 - $lng * 1) * ((float)$markers[$j]['longitude'] * 1 - $lng);
					$b = ((float)$markers[$j + 1]['latitude'] * 1 - $lat) * ((float)$markers[$j + 1]['latitude'] * 1 - $lat) + ((float)$markers[$j + 1]['longitude'] * 1 - $lng) * ((float)$markers[$j + 1]['longitude'] * 1 - $lng);
					if ($a > $b) {
						//右边大于左边，交换
						$temp = $markers[$j];
						$markers[$j] = $markers[$j + 1];
						$markers[$j + 1] = $temp;
					}
				}
			}
		}
		
		$this->success('', $markers);
	}
	
	/*余额明细*/
	/*用户积分明细列表*/
	public function moneyList()
	{
		$status = $this->request->post('status');//获取订单状态筛选 暂定0为全部，1=支出，2=收入  尚有下拉框筛选没做
		$where['user_id'] = $this->auth->id;
		if ($status == 1) $where['money'] = ['<', 0];
		if ($status == 2) $where['money'] = ['>', 0];
		
		$model = new \app\admin\model\UserMoneyLog();
		$list = $model->where($where)
			->order('id DESC')
			->select();
		foreach ($list as &$row) {
			$row['createtime_text'] = date("Y-m-d H:i:s", $row['createtime']);
		}
		$this->success('', $list);
	}
	
	/*上次下单的信息*/
	public function lastOrderInfo()
	{
		$detail = RecoveryOrder::where('order_user_id', $this->auth->id)->order('id DESC')->find();
		$this->success('', $detail);
	}
	
	/*申请提现*/
	public function withdrawal()
	{
		$user = $this->auth->getUser();
		$cost = $this->request->post('cost/f');
		$type = $this->request->post('type/d');
		$bank_account = $this->request->post('bank_account');
		$bank_username = $this->request->post('bank_username');
		$bank_name = $this->request->post('bank_name');
		$ali_username = $this->request->post('ali_username');
		$ali_account = $this->request->post('ali_account');
		if ($cost <= 0) $this->error("提现金额必须大于0");
		if ($cost > $user->money * 1) $this->error("提现金额不能大于账户余额");
		if ($type === 0) {
			if (!$bank_account) {
				$this->error("请填写银行卡号");
			}
			if (!$bank_username) {
				$this->error("请填写开户姓名");
			}
			if (!$bank_name) {
				$this->error("请填写开户行");
			}
		} else if ($type === 1) {
			if (!$ali_account) {
				$this->error("请填写支付宝账号");
			}
			if (!$ali_username) {
				$this->error("请填写支付宝用户名");
			}
		} else {
			$this->error("请选择提现方式");
		}
		/*变更用户的余额*/
		\app\common\model\User::money(-1 * $cost, $user->id, '用户提现');
		/*添加提现记录*/
		UserWithdrawal::create([
			'cost' => $cost,
			'type' => $type,
			'bank_account' => $bank_account,
			'bank_username' => $bank_username,
			'bank_name' => $bank_name,
			'ali_account' => $ali_account,
			'ali_username' => $ali_username,
			'user_id' => $user->id
		]);
		$this->success(__('提交申请成功'));
	}
}
